package com.purong.purong.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.alibaba.fastjson.JSON;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.purong.purong.Contant;
import com.purong.purong.R;
import com.purong.purong.activity.WebActivity;
import com.purong.purong.adapter.BankRecyAdapter;
import com.purong.purong.bean.ADInfo;
import com.purong.purong.bean.AdListBean;
import com.purong.purong.bean.BankBean;
import com.purong.purong.bean.CreditBankListBean;
import com.purong.purong.util.CommonUtil;
import com.purong.purong.util.CustomJsonParse;
import com.purong.purong.util.SharePreUtil;
import com.yao.sdk.glide.GlideUtil;
import com.yao.sdk.net.ResponseInfo;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wenjiezeng on 2017/9/28.
 */
public class QueryScheduleFragment extends BaseFragment {
    private RecyclerView mRecyclerView;
    private BankRecyAdapter mAdapter;
    private List<BankBean> bankList=new ArrayList<>();
    private View headView;
    private ConvenientBanner banner;
    private ImageView centerCbBg;
    private ImageView[] topIndicators;
    private LinearLayout indicatorLay;
    @Nullable


    @Override
    public int getRootViewId() {
        return R.layout.fragment_schedule_query;
    }

    public void initView(View v){
        headView = getActivity().getLayoutInflater().inflate(R.layout.query_schedule_head,null);
        banner = (ConvenientBanner) headView.findViewById(R.id.top_cb);
        indicatorLay=(LinearLayout)headView.findViewById(R.id.indicator_lay);
        centerCbBg=(ImageView)headView.findViewById(R.id.center_cb_bg);
        int topHeight = (int) (CommonUtil.getScreenWidth(getActivity()) * 0.344);
        RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, topHeight);
        banner.setLayoutParams(lp);
        centerCbBg.setLayoutParams(lp);


        mRecyclerView=(RecyclerView)v.findViewById(R.id.recycler_view);
        mRecyclerView.setLayoutManager(new GridLayoutManager(getActivity(),4));
        mAdapter=new BankRecyAdapter(getActivity());
        mAdapter.addHeaderView(headView);
        mAdapter.setOnBankClickListener(new BankRecyAdapter.OnBankClickListener() {
            @Override
            public void onBankClick(BankBean bank) {
                Intent intent=new Intent(getActivity(),WebActivity.class);
                intent.putExtra("TITLE", "申请进度查询");
                intent.putExtra("URL", bank.getCredit_schedule_url());
                intent.putExtra("TITLEBAR", true);
                startActivity(intent);
                setQuery(bank.getBank_id());
            }
        });
        mAdapter.setData(bankList);
        mRecyclerView.setAdapter(mAdapter);


    }

    @Override
    public void initData() {
        getAd();
        getBankList();
    }
    private void setQuery(String bankId){
        Map<String, String> topParams = new LinkedHashMap<String, String>();
        topParams.put("bank_id",bankId);
        request(Contant.CREDIT_SCHEDULE, topParams, true, false);

    }
    private void getAd(){
        Map<String, String> topParams = new LinkedHashMap<String, String>();
        topParams.put("location_code","CreditSchedule");
        topParams.put("city_id", SharePreUtil.getInstance(getActivity()).getLoactionAreaId());
        request(Contant.AD_IMG, topParams, true, false);

    }
    private void getBankList(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        request(Contant.CREDIT_BANK, params, true, false);
    }
    private void setAdInfo(final AdListBean adBean) {
        centerCbBg.setVisibility(View.GONE);
        banner.setPages(new CBViewHolderCreator<ImageViewHolder>() {
            @Override
            public ImageViewHolder createHolder() {
                return new ImageViewHolder(GlideUtil.HROIZONTAL);
            }
        }, adBean.getAd_list());
        if (adBean.getAd_list().size()>1){
            initTopIndicator(adBean);
            banner.startTurning(5000);
            banner.setCanLoop(true);
        }else {
            banner.setCanLoop(false);
        }


        banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                setTopIndicator(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        banner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (adBean.getAd_list().get(position).getAd_goto_url()!=null&&
                        (adBean.getAd_list().get(position).getAd_goto_url().startsWith("http")||adBean.getAd_list().get(position).getAd_goto_url().startsWith("HTTP"))){
                    Intent intent=new Intent(getActivity(),WebActivity.class);
                    intent.putExtra("TITLE", adBean.getAd_list().get(position).getAd_name());
                    intent.putExtra("URL", adBean.getAd_list().get(position).getAd_goto_url());
                    intent.putExtra("TITLEBAR", true);
                    startActivity(intent);
                }
            }
        });


    }
    private void setTopIndicator(int selectedPosition) {
        if (topIndicators == null)
            return;
        for (int i = 0; i < topIndicators.length; i++) {
            topIndicators[i]
                    .setImageResource(R.drawable.lunbodian_nor);
        }
        if (topIndicators.length > selectedPosition)
            topIndicators[selectedPosition]
                    .setImageResource(R.drawable.lunbodian_sel);
    }
    private void initTopIndicator(AdListBean mAdBean) {
        if (mAdBean != null && mAdBean.getAd_list() != null) {
            topIndicators = new ImageView[mAdBean.getAd_list().size()];
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(CommonUtil.dip2px(getActivity(), 10), CommonUtil.dip2px(getActivity(), 3));
            lp.setMargins(CommonUtil.dip2px(getActivity(), 3), 0, CommonUtil.dip2px(getActivity(), 3), 0);
            for (int i = 0; i < mAdBean.getAd_list().size(); i++) {
                ImageView indicatorImg = new ImageView(getActivity());
                if (i == 0) {
                    indicatorImg.setImageResource(R.drawable.lunbodian_sel);
                } else {
                    indicatorImg.setImageResource(R.drawable.lunbodian_nor);

                }
                indicatorImg.setLayoutParams(lp);
                indicatorLay.addView(indicatorImg);
                topIndicators[i] = indicatorImg;
            }

        }
    }

    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy())
            return;
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.CREDIT_BANK)){
            if (responseInfo.isRequestOk){
                try{
                    CreditBankListBean bankListBean= JSON.parseObject(responseInfo.content,CreditBankListBean.class);
                    if (bankListBean!=null&&bankListBean.getBank_list()!=null){
                        bankList.clear();
                        bankList.addAll(bankListBean.getBank_list());

                        mAdapter.notifyDataSetChanged();
                    }
                }catch (Exception e){

                }
            }
        }else if (responseInfo.url.equals(Contant.AD_IMG)){
            if (responseInfo.isRequestOk){
                try{
                    AdListBean bean=JSON.parseObject(responseInfo.content,AdListBean.class);
                    if (bean!=null&&bean.getAd_list()!=null&&bean.getAd_list().size()>0){
                        setAdInfo(bean);
                    }
                }catch (Exception e){

                }
            }
        }else if (responseInfo.url.equals(Contant.CREDIT_SCHEDULE)){
            if (responseInfo.isRequestOk){

            }
        }
    }


    public class ImageViewHolder implements Holder<ADInfo> {
        private ImageView imageView;
        private int placeHolderType;

        public ImageViewHolder(int placeHolderType) {
            this.placeHolderType=placeHolderType;
        }

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, ADInfo data) {
            GlideUtil.getInstance().load(getActivity(), data.getAd_photo_url(), imageView, true,placeHolderType);
        }
    }
}
